package demoflink.state;

import demoflink.entity.WaterSensor;
import demoflink.function.WaterSensorMapFunction;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.common.state.StateTtlConfig;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.time.Time;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.connector.kafka.source.KafkaSource;
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * 检测每种检测器 如果差值超过10进行报警
 */
public class KeyedValueStateWithTTLDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.createLocalEnvironmentWithWebUI(new Configuration());
        KafkaSource<String> kafkaSource = KafkaSource.<String>builder()
                .setBootstrapServers("node1:9092,node2:9092,node3:9092")
                .setGroupId("local")
                .setTopics("first")
                .setValueOnlyDeserializer(new SimpleStringSchema())
                .setStartingOffsets(OffsetsInitializer.latest())
                .build();
        env.setParallelism(1);

        // 指定水位线
        WatermarkStrategy<WaterSensor> strategy = WatermarkStrategy
                //乱序
                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                .withTimestampAssigner((element,ts)-> element.getTs()*1000L);
        env.fromSource(kafkaSource, WatermarkStrategy.noWatermarks(), "kafkaSource")
                .map(new WaterSensorMapFunction())
                .assignTimestampsAndWatermarks(strategy)
                .keyBy(x -> x.getId())
                .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                    ValueState<Integer> lastState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        super.open(parameters);
                        StateTtlConfig stateTtlConfig = StateTtlConfig
                                .newBuilder(Time.seconds(5))
                                .setUpdateType(StateTtlConfig.UpdateType.OnCreateAndWrite)
                                .setStateVisibility(StateTtlConfig.StateVisibility.NeverReturnExpired)
                                .build();
                        ValueStateDescriptor<Integer> descriptor = new ValueStateDescriptor<>("lastState", Types.INT);
                        descriptor.enableTimeToLive(stateTtlConfig);
                        lastState = getRuntimeContext().getState(descriptor);
                    }

                    @Override
                    public void processElement(WaterSensor waterSensor, KeyedProcessFunction<String, WaterSensor, String>.Context context, Collector<String> collector) throws Exception {
                        //取出上一条水位线的值
                        int i = lastState.value() == null ? 0 : lastState.value();
                        //求差值的绝对值判断是否超过10
                        Integer vc = waterSensor.getVc();
                        if (Math.abs(vc-i)>10) {
                            collector.collect("传感器"+ waterSensor.getId()+":当前水位值="+vc+",与上一条水位线值="+i+",相差"+Math.abs(vc-i));
                        }
                        //更新水位线值
                        lastState.update(vc);
                    }
                })
                .print();
        env.execute();
    }
}
